package com.example.demo.utils;

import com.example.demo.vo.app.AppVO;
import com.example.demo.vo.picture.PictureVO;
import com.example.demo.vo.task.TaskDocVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Slf4j
public class FileHelper {

    private static void checkDirectoryPath(String directoryPath) {
        File dir = new File(directoryPath);
        if (!dir.exists() && !dir.isDirectory()) {
            log.debug("用于存放上传文件的文件夹不存在，正在尝试创建..");
            dir.mkdirs();
        }
    }

    private static String save(String directoryPath, MultipartFile file) throws IOException {
        checkDirectoryPath(directoryPath);
        // 原文件名
        String originalName = file.getOriginalFilename();
        String newName = UUID.randomUUID() + "-" + originalName;
        // 根据目标地址构造文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream(directoryPath + newName);
        // 将文件复制到映射的地址
        FileCopyUtils.copy(file.getInputStream(), fileOutputStream);
        return newName;
    }

    public static AppVO saveApp(String directoryPath, MultipartFile file) throws IOException {
        String originalName = file.getOriginalFilename();
        String newName = save(directoryPath, file);
        return new AppVO(originalName, newName);
    }

    public static PictureVO savePicture(String directoryPath, MultipartFile file) throws IOException {
        String newName = save(directoryPath, file);
        return new PictureVO(newName);
    }

    public static TaskDocVO saveDoc(String directoryPath, MultipartFile file) throws IOException {
        String newName = save(directoryPath, file);
        return new TaskDocVO(newName);
    }

    /**
     * 加载文件为资源
     *
     * @param directoryPath 目录路径（以 / 结尾）
     * @param fileName      文件名
     * @return 输入流资源
     */
    public static Resource loadFileAsResource(String directoryPath, String fileName) throws IOException {
        Path filePath = Paths.get(directoryPath + fileName);
        Resource resource = new UrlResource(filePath.toUri());
        if (resource.exists())
            return resource;
        return null;
    }

    public static boolean delete(String directoryPath, String fileName) {
        if (StringUtils.hasText(fileName)) {
            File file = new File(directoryPath + fileName);
            if (file.exists()) {
                // 当且仅当文件被成功删除后返回true
                return file.delete();
            }
        }
        return false;
    }

}
